function [bc_capacity, fig_handle] = downlink_capacity(SNR_dB, num_users)
% 下行链路BC容量分析
% 输入:
%   SNR_dB - 信噪比范围 (dB)
%   num_users - 用户数量数组
% 输出:
%   bc_capacity - BC容量矩阵
%   fig_handle - 图形句柄

    SNR_linear = 10.^(SNR_dB/10);
    bc_capacity = zeros(length(SNR_dB), length(num_users));
    
    % 添加路径
    addpath('../Common');
    colors = color_definitions();
    
    fprintf('=== 下行链路BC容量分析 ===\n');
    
    for user_idx = 1:length(num_users)
        K = num_users(user_idx);
        fprintf('仿真 %d 用户BC容量...\n', K);
        
        for snr_idx = 1:length(SNR_dB)
            snr = SNR_linear(snr_idx);
            
            % 生成用户信道 (信道强度递减)
            base_channel = sqrt(0.5) * (randn(1, K) + 1i * randn(1, K));
            user_channels = base_channel .* (1 - 0.1*(0:K-1)); % 信道衰减
            
            % BC容量计算 (脏纸编码简化模型)
            [sorted_channels, ~] = sort(abs(user_channels), 'descend');
            
            remaining_power = 1;
            sum_rate = 0;
            
            for k = 1:K
                user_power = remaining_power / (K - k + 1);
                user_snr = snr * sorted_channels(k)^2 * user_power;
                
                interference_power = remaining_power - user_power;
                sinr = user_snr / (1 + snr * sorted_channels(k)^2 * interference_power);
                
                if sinr > 0
                    sum_rate = sum_rate + log2(1 + sinr);
                end
                
                remaining_power = remaining_power - user_power;
            end
            
            bc_capacity(snr_idx, user_idx) = sum_rate;
        end
    end
    
    % 绘制结果
    fig_handle = figure('Name', '下行链路BC容量', 'Position', [150, 150, 800, 600]);
    
    subplot(1,2,1);
    for user_idx = 1:length(num_users)
        plot(SNR_dB, bc_capacity(:, user_idx), ...
             ['-', colors(user_idx)], 'LineWidth', 2);
        hold on;
    end
    grid on;
    xlabel('SNR (dB)');
    ylabel('和速率 (bps/Hz)');
    title('广播信道容量');
    legend(arrayfun(@(x) sprintf('%d用户', x), num_users, 'UniformOutput', false));
    
    % MAC vs BC 容量比较
    subplot(1,2,2);
    K = 4; % 比较4用户情况
    if ismember(K, num_users)
        user_idx = find(num_users == K, 1);
        % 这里需要重新计算MAC容量进行比较
        [mac_capacity, ~] = uplink_capacity(SNR_dB, K);
        
        plot(SNR_dB, mac_capacity(:, 1), 'b-', 'LineWidth', 2);
        hold on;
        plot(SNR_dB, bc_capacity(:, user_idx), 'r--', 'LineWidth', 2);
        grid on;
        xlabel('SNR (dB)');
        ylabel('和速率 (bps/Hz)');
        title(sprintf('%d用户: MAC vs BC容量', K));
        legend('MAC (上行)', 'BC (下行)', 'Location', 'NorthWest');
    end
end